#include "friendwindow.h"
#include "ui_friendwindow.h"
#include "login.h"
#include "protocol.h"
#include <QMenu>
#include<QMessageBox>
#include"chatuserwid.h"

FriendWindow::FriendWindow(QWidget *parent) :
    QWidget(parent),
  ui(new Ui::FriendWindow)
{
    ui->setupUi(this);
    m_paddUserW = new addfriend;
    m_paddUserW->hide();
    ui->m_pFriendListWidgt->setProperty("contextMenuPolicy", Qt::CustomContextMenu);
    popMenu_In_ListWidget_ = new QMenu(this);
    action_Delete_In_ListWidget_ = new QAction(tr("Delete"), this);
    popMenu_In_ListWidget_->addAction(action_Delete_In_ListWidget_);
    connect(this->action_Delete_In_ListWidget_, SIGNAL(triggered()),
            this, SLOT(deleteFriend()));
    connect(ui->m_pFriendListWidgt, SIGNAL(customContextMenuRequested(const QPoint &)),
            this, SLOT(onCustomContextMenuRequested(const QPoint &)));
    connect(ui->m_pFriendListWidgt, &QListWidget::itemDoubleClicked, this, &FriendWindow::onFriendDoubleClicked);
    on_friend_pb_clicked();
}

FriendWindow::~FriendWindow()
{
    delete ui;
}

void FriendWindow::setOnlineUsers(PDU *pdu)
{
    if(NULL == pdu)
    {
        return ;
    }
    m_paddUserW->setOnlineUsers(pdu);
}

void FriendWindow::updateFriendList(PDU *pdu)
{
    if(NULL == pdu)
    {
        return ;
    }
    uint uiSize = pdu -> uiMsgLen / 36; // 注意是36，32 name + 4 online
    char caName[32] = {'\0'};
    char caOnline[4] = {'\0'};

    ui->m_pFriendListWidgt -> clear(); // 清除好友列表原有数据
    for(uint i = 0; i < uiSize; ++ i)
    {
        memcpy(caName, (char*)(pdu -> caMsg) + i * 36, 32);
        memcpy(caOnline, (char*)(pdu -> caMsg) + 32 + i * 36, 4);
        QString name = QString("%1").arg(caName);
        QString online = strcmp(caOnline, "1") == 0 ? "在线" : "离线";
        auto *chat_user_wid = new ChatUserWid();
        chat_user_wid->SetInfo(name,":/res/head.jpg", online);
        QListWidgetItem *item = new QListWidgetItem;
        //qDebug()<<"chat_user_wid sizeHint is " << chat_user_wid->sizeHint();
        item->setSizeHint(chat_user_wid->sizeHint());
        ui->m_pFriendListWidgt->addItem(item);
        ui->m_pFriendListWidgt->setItemWidget(item, chat_user_wid);
//        QListWidgetItem *item = new QListWidgetItem(QString("%1\t%2").arg(name).arg(online));
//        item->setData(Qt::UserRole, online); // 存储在线状态信息
//        ui->m_pFriendListWidgt -> addItem(item);
    }
}

void FriendWindow::sayFriendList(PDU *pdu)
{
    if(NULL == pdu)
    {
        return ;
    }
    char caSendName[32] = {'\0'};
    strncpy(caSendName, pdu -> caData + 32, 32);
    QString strMsg = QString("%1 : %2").arg(caSendName).arg((char*)pdu -> caMsg);
    ui -> showMsg_te -> append(strMsg);
}

void FriendWindow::setChatName(QString strName)
{
    m_setChatName = strName;
}

QString FriendWindow::strLoginName() const
{
    return m_strLoginName;
}

void FriendWindow::setStrLoginName(const QString &strLoginName)
{
    m_strLoginName = strLoginName;
}


FriendWindow &FriendWindow::getInstance()
{
    static FriendWindow instance;
    return instance;
}





void FriendWindow::on_m_addFriendPB_clicked()
{
    if(m_paddUserW -> isHidden())
    {
        m_paddUserW -> show();
        PDU *pdu = mkPDU(0);
        pdu -> uiMsgType = ENUM_MSG_TYPE_ONLINE_USERS_REQUEST;
        login::getInstance().getTcpSocket().write((char*)pdu, pdu -> uiPDULen);
        free(pdu);
        pdu = NULL;
    }
    else
    {
        m_paddUserW -> hide();
    }
}

void FriendWindow::on_friend_pb_clicked()
{
    QString strName = login::getInstance().getStrName();
    PDU* pdu = mkPDU(0);
    pdu -> uiMsgType = ENUM_MSG_TYPE_FLSUH_FRIEND_REQUEST;
    strncpy(pdu -> caData, strName.toStdString().c_str(), strName.size());
    login::getInstance().getTcpSocket().write((char*)pdu, pdu -> uiPDULen);
    free(pdu);
    pdu = NULL;
}

void FriendWindow::onCustomContextMenuRequested(const QPoint &pos)
{
    popMenu_In_ListWidget_->exec(QCursor::pos());
}

void FriendWindow::deleteFriend()
{
    if(NULL == ui->m_pFriendListWidgt -> currentItem())
    {
        return ;
    }
    QString friName = ui->m_pFriendListWidgt -> currentItem() -> text();
    friName = friName.split("\t")[0];
    QString loginName = login::getInstance().getStrName();

    qDebug() << friName;
    PDU* pdu = mkPDU(0);
    pdu -> uiMsgType = ENUM_MSG_TYPE_DELETE_FRIEND_REQUEST;
    strncpy(pdu -> caData, friName.toStdString().c_str(), 32);
    strncpy(pdu -> caData + 32, loginName.toStdString().c_str(), 32);
    login::getInstance().getTcpSocket().write((char*)pdu, pdu -> uiPDULen);
    free(pdu);
    pdu = NULL;
}

void FriendWindow::onFriendDoubleClicked(QListWidgetItem *item)
{
    if (!item) return;

    ChatUserWid *chatUserWid = qobject_cast<ChatUserWid*>(ui->m_pFriendListWidgt->itemWidget(item));
    if (chatUserWid) {
        QString friendName = chatUserWid->GetName();            // 从 ChatUserWid 获取好友名称
        QString caOnline = chatUserWid->GetOnlineStatus();      // 从 ChatUserWid 获取在线状态
        qDebug() << "好友在线状态：" << caOnline;
        qDebug() << "双击好友：" << friendName;
    m_caOnline=caOnline;
    m_setChatName =friendName;
    ui->label->setText(m_setChatName);
    ui->showMsg_te -> clear();
    QString m_strLoginName = login::getInstance().getStrName();
     qDebug() <<m_strLoginName;
    } else {
           qDebug() << "无法获取 ChatUserWid 对象";
       }
}

void FriendWindow::on_sendMsg_pb_clicked()
{
    QString strSendMsg = ui->inputMsg_le->text();
    QString m_strLoginName = login::getInstance().getStrName();
    if (m_setChatName==NULL) {
        QMessageBox::warning(this, "私聊", "请选择聊天对象！");
        ui -> inputMsg_le -> clear(); // 清空输入框内容
        return;
    }
    if (m_caOnline=="离线") {
        QMessageBox::warning(this, "私聊", "聊天对象不在线！");
        ui -> inputMsg_le -> clear(); // 清空输入框内容
        return;
    }
    if (strSendMsg.isEmpty()) {
        QMessageBox::warning(this, "私聊", "发送消息不能为空！");
        return;
    }

    PDU *pdu = (PDU*)malloc(sizeof(PDU) + strSendMsg.size() * sizeof(char));
    if (pdu == NULL) {
        qDebug() << "Failed to allocate memory for PDU.";
        return;
    }
    ui -> inputMsg_le -> clear();
    ui -> showMsg_te -> append(QString("%1 : %2").arg(m_strLoginName).arg(strSendMsg));
    pdu->uiMsgType = ENUM_MSG_TYPE_PRIVATE_CHAT_REQUEST;
    strncpy(pdu->caData, m_setChatName.toStdString().c_str(), 32);
    pdu->caData[31] = '\0';
    strncpy(pdu->caData + 32, m_strLoginName.toStdString().c_str(), 32);
    pdu->caData[63] = '\0';

    QByteArray msgBytes = strSendMsg.toUtf8();
    pdu->uiMsgLen = msgBytes.size(); // 设置实际消息长度
    memcpy(pdu->caMsg, msgBytes.data(), pdu->uiMsgLen);// 复制消息内容

    pdu->uiPDULen = sizeof(PDU) + pdu->uiMsgLen * sizeof(int);
    login::getInstance().getTcpSocket().write((char*)pdu, pdu->uiPDULen);
    free(pdu);

}
